package com.sec.moveFile.utils;

import com.emc.ecs.nfsclient.nfs.io.Nfs3File;
import com.emc.ecs.nfsclient.nfs.io.NfsFileInputStream;
import com.emc.ecs.nfsclient.nfs.nfs3.Nfs3;
import com.emc.ecs.nfsclient.rpc.CredentialUnix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


/**
 * @author 68300119
 * @Date 2021/5/12
 **/
@Component
public class NFSUtils {
    private final static Logger log = LoggerFactory.getLogger(NFSUtils.class);

    @Value("${ssc.attachment.path:}")
    private String path;

    @Value("${ssc.attachment.nfs.enabled:false}")
    private boolean nfsEnabled;

    @Value("${ssc.attachment.nfs.ip:}")
    private String nfsIp;

    @Value("${ssc.attachment.nfs.export:}")
    private String nfsExport;

    private Nfs3 nfs3 = null;


    @PostConstruct
    public void init() throws IOException {
        nfs3 = new Nfs3(nfsIp, nfsExport, new CredentialUnix(), 1);
    }


    public Resource download(String url) {
        Path filePath = Paths.get(path, url);
        Resource resource;

        if (nfsEnabled) {
            try {
                url = url.replaceAll("\\\\", "/");
                Nfs3File nfs3File = new Nfs3File(nfs3, "/" + url);
                if (!nfs3File.exists()) {
                    throw new RuntimeException("文件未找到");
                }

                resource = new InputStreamResource(new NfsFileInputStream(nfs3File));
            } catch (IOException e) {
                log.error("Get file from nfs failed:{}", e.getMessage());
                throw new RuntimeException("文件未找到" + e.getMessage());
            }
        } else {
            if (!Files.exists(filePath)) {
                throw new RuntimeException("文件未找到");
            }
            try {
                resource = new UrlResource(filePath.toUri());
            } catch (MalformedURLException e) {
                log.error("Get resource from url failed:{}", e.getMessage());
                throw new RuntimeException("文件未找到" + e.getMessage());
            }
        }
        return resource;
    }
}
